﻿using System;
using System.Collections;
using GameCreator.Core;
using PixelCrushers.DialogueSystem;

using UnityEngine;

namespace Gp.GCX {
    [AddComponentMenu("")]
    public class DlsTriggerAc : IAction {
        public DialogueSystemTrigger dlsTrigger;
        public bool asyncExecute;

        private void Reset() {
            if (dlsTrigger || (dlsTrigger = this.GetComponentInChildren<DialogueSystemTrigger>())) return;
            dlsTrigger = this.gameObject.AddComponent<PixelCrushers.DialogueSystem.Wrappers.DialogueSystemTrigger>();
            dlsTrigger.trigger = DialogueSystemTriggerEvent.None;
        }


        public override bool InstantExecute(GameObject target, IAction[] actions, int index) {
            if (!asyncExecute) return false;
        
            StartCoroutine(Process());
            return true;
        }


        public override IEnumerator Execute(GameObject target, IAction[] actions, int index) {
            yield return Process();
        }


        private IEnumerator Process() {
            dlsTrigger.TryStart(null);
            
            // 持续至对话结束
            while (DialogueManager.instance.isConversationActive) {
                yield return 0;
            }
        }


#if UNITY_EDITOR
        public new static string NAME = "Gp/调用DLS-Trigger";
        private const string NODE_TITLE = "调用DLS-Trigger";

        public override string GetNodeTitle() {
            return NODE_TITLE;
        }


        // public void OnDestroy() {
        //     if (Application.isPlaying) return;
        //     if (dlsTrigger != null) {
        //         DestroyImmediate(dlsTrigger);
        //     }
        // }
#endif
    }
}